package com.lp.demo8;

import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;

import java.util.Random;

public class MinesweeperBoard {
    private final int size;
    private final int mineCount;
    private final Cell[][] cells;
    private boolean gameOver;
    private int remainingCells;

    public MinesweeperBoard(int size, int mineCount) {
        this.size = size;
        this.mineCount = mineCount;
        this.cells = new Cell[size][size];
        this.gameOver = false;
        this.remainingCells = size * size - mineCount;
        initializeBoard();
    }

    public GridPane createBoard() {
        GridPane gridPane = new GridPane();
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                Button button = createCellButton(row, col);
                gridPane.add(button, col, row);
            }
        }
        return gridPane;
    }

    private Button createCellButton(int row, int col) {
        Button button = new Button();
        button.setMinSize(30, 30);
        button.setMaxSize(30, 30);
        button.setFont(Font.font(12));

        button.setOnMouseClicked(event -> {
            if (gameOver) return;
            
            if (event.getButton() == MouseButton.PRIMARY) {
                handleLeftClick(row, col, button);
            } else if (event.getButton() == MouseButton.SECONDARY) {
                handleRightClick(button);
            }
        });

        cells[row][col].setButton(button);
        return button;
    }

    private void handleLeftClick(int row, int col, Button button) {
        Cell cell = cells[row][col];
        if (cell.isFlagged()) return;

        if (cell.isMine()) {
            gameOver = true;
            revealAllMines();
            showGameOverAlert(false);
            return;
        }

        revealCell(row, col);
        
        if (remainingCells == 0) {
            gameOver = true;
            showGameOverAlert(true);
        }
    }

    private void handleRightClick(Button button) {
        Cell cell = getCellByButton(button);
        if (cell.isRevealed()) return;

        if (cell.isFlagged()) {
            button.setText("");
            cell.setFlagged(false);
        } else {
            button.setText("🚩");
            cell.setFlagged(true);
        }
    }

    private void initializeBoard() {
        // Initialize cells
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                cells[row][col] = new Cell();
            }
        }

        // Place mines
        Random random = new Random();
        int minesPlaced = 0;
        while (minesPlaced < mineCount) {
            int row = random.nextInt(size);
            int col = random.nextInt(size);
            if (!cells[row][col].isMine()) {
                cells[row][col].setMine(true);
                minesPlaced++;
            }
        }

        // Calculate numbers
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                if (!cells[row][col].isMine()) {
                    cells[row][col].setNumber(countAdjacentMines(row, col));
                }
            }
        }
    }

    private int countAdjacentMines(int row, int col) {
        int count = 0;
        for (int r = -1; r <= 1; r++) {
            for (int c = -1; c <= 1; c++) {
                int newRow = row + r;
                int newCol = col + c;
                if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size) {
                    if (cells[newRow][newCol].isMine()) {
                        count++;
                    }
                }
            }
        }
        return count;
    }

    private void revealCell(int row, int col) {
        Cell cell = cells[row][col];
        if (cell.isRevealed() || cell.isFlagged()) return;

        cell.setRevealed(true);
        Button button = cell.getButton();
        
        if (cell.getNumber() > 0) {
            button.setText(String.valueOf(cell.getNumber()));
        } else {
            button.setText("");
            // Reveal adjacent cells if this is an empty cell
            for (int r = -1; r <= 1; r++) {
                for (int c = -1; c <= 1; c++) {
                    int newRow = row + r;
                    int newCol = col + c;
                    if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size) {
                        revealCell(newRow, newCol);
                    }
                }
            }
        }
        
        button.setStyle("-fx-background-color: lightgray;");
        remainingCells--;
    }

    private void revealAllMines() {
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                if (cells[row][col].isMine()) {
                    cells[row][col].getButton().setText("💣");
                    cells[row][col].getButton().setStyle("-fx-background-color: red;");
                }
            }
        }
    }

    private void showGameOverAlert(boolean won) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("游戏结束");
        alert.setHeaderText(null);
        alert.setContentText(won ? "恭喜你赢了！" : "游戏结束！");
        alert.show();
    }

    private Cell getCellByButton(Button button) {
        for (Cell[] row : cells) {
            for (Cell cell : row) {
                if (cell.getButton() == button) {
                    return cell;
                }
            }
        }
        return null;
    }
} 